import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import React, { useState, useEffect, useRef } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import {
  useAppDispatch,
  useAppSelector,
} from "../../../../../utils/store/hooks";
import {
  fetchClipboard,
  setClipboard,
  setLoading,
  stashClipboard,
} from "../../../../../utils/store/clipboardSlice";
import { useHotKey } from "../../../../../utils/utils/shortcut";
import { clipboardApi, uploadApi } from "../../../../../utils/backend/server";
import _ from "lodash";
import { toast } from "../../../../../components/Toast/Toast";
import { addMemo } from "../../Memo/Memo";
import { UPLOAD_RESOURCE } from "../../../../../utils/utils/request";
import { store } from "../../../../../utils/store/store";
import { updateLogin } from "../../../../../utils/store/deviceSlice";

let stopLoading = () => {};

const save = _.debounce(async (text) => {
  await clipboardApi.setClipboard(text);
  stopLoading();
}, 500);

type InsertFnType = (url: string, alt: string, href: string) => void;

export const RichTextEditor = () => {
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "never stop learning...",
    MENU_CONF: {
      uploadImage: {
        server: uploadApi.upload(),
        fieldName: "file",
        allowedFileTypes: [],
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
        async customUpload(file: File, insertFn: InsertFnType) {
          const fd = new FormData();
          fd.append("file", file);
          fd.append("path", "/");
          const {
            data: { msg, code, success, data },
          } = await uploadApi.uploadFiles(fd);
          if (code === 401) return store.dispatch(updateLogin(true));
          const [img] = data;
          insertFn(UPLOAD_RESOURCE + img, img, UPLOAD_RESOURCE + img);
        },
      },
    },
  };

  const hotKey = useHotKey("s");
  const html = useAppSelector((state) => state.clipboard.text);
  const dispatch = useAppDispatch();

  const setTextWithLoading = (text: string) => {
    stopLoading = () => dispatch(setLoading(false));
    dispatch(setLoading(true));
    dispatch(setClipboard(text));
    save(text);
  };

  useEffect(() => {
    if (editor === null) return;
    dispatch(fetchClipboard());
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  useEffect(() => {
    hotKey && dispatch(stashClipboard());
  }, [hotKey]);

  const onChange = (editor: IDomEditor) => {
    const html = editor.getHtml();
    // console.log(html);

    setTextWithLoading(html);
  };

  return (
    <>
      <div
        style={{
          border: "1px solid #ccc",
          height: "100%",
          zIndex: 100,
          minHeight: "50vh",
        }}
      >
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          value={html}
          defaultConfig={editorConfig}
          onChange={onChange}
          onCreated={setEditor}
          mode="default"
          style={{ width: "90vw", cursor: " url(/text.cur), default" }}
        />
      </div>
    </>
  );
};
